package conversores;

import javax.el.ValueExpression;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import cars.CarObject;
import cars.CarsBean;

@FacesConverter(forClass=CarObject.class)
public class CarConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) {
		if (context == null) {throw new NullPointerException("context");}
		if (component == null) {throw new NullPointerException("component");}
		FacesContext ctx = FacesContext.getCurrentInstance();
		ValueExpression vex =
				ctx.getApplication().getExpressionFactory()
					.createValueExpression(ctx.getELContext(), "#{carsBean}", CarsBean.class);
		CarsBean cars = (CarsBean)vex.getValue(ctx.getELContext());
		CarObject car = null;
		try {
			car = cars.getCar(new Integer (value));
		} catch (NumberFormatException e) {
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unknown value", "This is not a car number!");
			throw new ConverterException(message);
		}
		if (car == null) {
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unknown value", "The car is unknown!");
			throw new ConverterException(message);
		}
		return car;
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object value) {
		if (context == null) {throw new NullPointerException("context");}
		if (component == null) {throw new NullPointerException("component");}
		return ((CarObject) value).getCarNumber().toString();
	}

}
